package com.brtbeacon.wx.demo.mapview;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.brtbeacon.wx.map.v2.BRTWebViewDelegate;
import com.brtbeacon.wx.map.v2.BRTWebViewPlugin;
import com.brtbeacon.wx.map.v2.DefaultWebViewDelegate;

import java.util.ArrayList;
import java.util.List;

public class MapWebViewPluginActivity extends AppCompatActivity {

    public static final String TAG = MapWebViewPluginActivity.class.getSimpleName();
    public static final  String PARAM_URL = "param_url";
    private static final int REQUEST_PLUGIN_PERMISSIONS = 1;
    private static final int REQUEST_ENABLE_BT = 1001;
    private static final int REQUEST_ENABLE_GPS = 1002;

    private FrameLayout webViewContainer;
    private WebView webView;
    private BRTWebViewPlugin webViewPlugin;

    public static void startActivity(Context ctxt, String url) {
        Intent intent = new Intent(ctxt, MapWebViewPluginActivity.class);
        intent.putExtra(PARAM_URL, url);
        ctxt.startActivity(intent);
    }

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view_plugin);

        IntentFilter statusFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(btStateBroadcastReceive, statusFilter);

        //  检查权限
        checkPermissions();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(btStateBroadcastReceive);
        if (webViewPlugin != null) {
            webViewPlugin.onDestroy();
        }
    }

    private void initWebView() {

        if (webView != null)
            return;

        webView = findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setMediaPlaybackRequiresUserGesture(false);

        //  WebView上级容器，必须为FrameLayout;
        webViewContainer = findViewById(R.id.rootView);
        BRTWebViewDelegate webViewDelegate = new DefaultWebViewDelegate(webView) {
            @Override
            public View getWebViewContainer() {
                return webViewContainer;
            }
        };

        webViewPlugin = new BRTWebViewPlugin(this, webViewDelegate) {
            @Override
            protected void onRequestLocation() {
                // 当页面调用定位功能时，检查蓝牙和GPS开启状态。
                checkNeedEnable();
            }
        };

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http")) {
                    try {
                        // 以下固定写法
                        final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
                final boolean remember = true;
                AlertDialog.Builder builder = new AlertDialog.Builder(MapWebViewPluginActivity.this);
                builder.setTitle("位置信息");
                builder.setMessage(origin + "允许获取您的地理位置信息吗？").setCancelable(true).setPositiveButton("允许",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        callback.invoke(origin, true, remember);
                                    }
                                })
                        .setNegativeButton("不允许",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        callback.invoke(origin, false, remember);
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();
            }

            @Override
            public void onPermissionRequest(final PermissionRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MapWebViewPluginActivity.this);
                    builder.setTitle("权限申请");
                    StringBuilder sb = new StringBuilder();
                    for (String s: request.getResources()) {
                        if (sb.length() != 0) {
                            sb.append(",");
                        }
                        if (s.equals(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) {
                            sb.append("录音");
                        } else if (s.equals(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) {
                            sb.append("录相");
                        }
                    }
                    builder.setMessage("允许获取" + sb.toString() + "权限吗？").setCancelable(true).setPositiveButton("允许",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int id) {
                                            request.grant(request.getResources());
                                        }
                                    })
                            .setNegativeButton("不允许",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int id) {
                                            request.deny();
                                        }
                                    });
                    AlertDialog alert = builder.create();
                    alert.show();
                } else {
                    super.onPermissionRequest(request);
                }
            }
        });


        String url = getIntent().getStringExtra(PARAM_URL);
        if (TextUtils.isEmpty(url)) {
            url = "";
        }
        //Log.d(TAG, "加载地址: " + url);
        webView.loadUrl(url);
    }

    private void checkPermissions() {

        List<String> permissions = new ArrayList<>();

        //  X5引擎初始化权限
        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);

        //  GPS和室内定位权限
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);

        //  二维码扫描功能
        permissions.add(Manifest.permission.CAMERA);

        // 如果页面需要调用语音转文字功能, 请移除下行代码注释
        //permissions.add(Manifest.permission.RECORD_AUDIO);

        // 安卓12及以上系统请添加以下权限声明，用于蓝牙打开和Beacon信标扫描
        if (Build.VERSION.SDK_INT >= 31) {
            permissions.add(Manifest.permission.BLUETOOTH_CONNECT);
            permissions.add(Manifest.permission.BLUETOOTH_SCAN);
        }

        List<String> checkPermissionList = new ArrayList<>();

        for (String permission: permissions) {
            if (this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                checkPermissionList.add(permission);
            }
        }

        if (!checkPermissionList.isEmpty()) {
            requestPermissions(checkPermissionList.toArray(new String[1]), REQUEST_PLUGIN_PERMISSIONS);
            return;
        }

        initWebView();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == REQUEST_PLUGIN_PERMISSIONS) {//  权限申请成功!
                initWebView();
            }
    }

    private void checkNeedEnable() {
        if (checkBtNeedEnable())
            return;
        checkGpsNeedEnable();
    }

    private boolean checkBtNeedEnable() {
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null)
            return false;

        if (bluetoothAdapter.isEnabled())
            return false;

        //  如果用户没有确认权限，就跳过打开蓝牙
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        //  请求打开蓝牙开关
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, REQUEST_ENABLE_BT);
        return true;
    }

    private boolean checkGpsNeedEnable() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提醒")
                .setMessage("定位功能将受限制：当前设备GPS未打开！是否确认打开GPS开关？")
                .setPositiveButton("确认", (dialog12, which) -> {
                    dialog12.dismiss();
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, REQUEST_ENABLE_GPS);
                })
                .setNegativeButton("忽略", (dialog1, which) -> dialog1.dismiss())
                .setCancelable(false)
                .create();
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.show();
        return true;
    }

    private final BroadcastReceiver btStateBroadcastReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
            if (blueState == BluetoothAdapter.STATE_ON) {
                checkGpsNeedEnable();
            }
        }
    };
}
